package com.mk.exception;

import com.alibaba.fastjson.JSONObject;
import com.mk.common.util.http.AjaxResult;
import com.mk.common.util.http.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class RestApiControlAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResult handle(MethodArgumentNotValidException ex){
        String message="";
        try{
            message = ex.getBindingResult().getFieldError().getDefaultMessage();
            return AjaxResult.error(HttpStatus.ERROR,message);
        }catch (NullPointerException ne){
            return AjaxResult.error(HttpStatus.ERROR,message);
        }
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public AjaxResult handle(ConstraintViolationException ex){
        List<String> msgList =new ArrayList<String>();
        for (ConstraintViolation<?> constraintViolation : ex.getConstraintViolations()) {
            msgList.add(constraintViolation.getMessage());
        }
        String messages = StringUtils.join(msgList.toArray(), ";");
        return AjaxResult.error(HttpStatus.ERROR,messages);
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public AjaxResult handle(HttpMessageNotReadableException ex){
        return AjaxResult.error(HttpStatus.ERROR,"json转换错误，请检查");
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JSONObject handle(Exception ex){
        //添加日志

        JSONObject object = new JSONObject();
        ex.printStackTrace();
        object.put("code",400);
        object.put("message","json转换错误，请检查");
        return object;
    }

}
